package com.wanmei.exception;

import com.google.gson.Gson;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.HostUnauthorizedException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WanmeiExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception e) {
        String message = "系统异常，请重试!";
        int code = 999999;
        //判断是否是自己抛出来的异常,如果是 将异常信息放到这边来.
        if (e instanceof WanmeiException) {
            message = ((WanmeiException) e).getMessage();
        }
        if (e instanceof UnauthenticatedException || e instanceof AuthorizationException) {
            code=3;
            message = "您的权限不能进行此操作！";
        } else if (e instanceof UnauthorizedException || e instanceof HostUnauthorizedException) {
            code=4;
            message = "您的角色没有权限访问";

        }
        //先判断是不是ajax，如果是responseBody 就传json回去.
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody != null) {
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("code", 0);
            responseMap.put("msg", message);
            String json = new Gson().toJson(responseMap);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            try {
                resp.getWriter().write(json);
                resp.getWriter().flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            //返回一个空的ModelAndView表示已经手动生成响应
            return new ModelAndView();
        }
        //向控制台打印异常
        e.printStackTrace();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code",code);
        modelAndView.addObject("msg", message);
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
